package cn.tedu._05mvcboot02.controller;

import cn.tedu._05mvcboot02.common.response.JsonResult;
import cn.tedu._05mvcboot02.mapper.UserMapper;
import cn.tedu._05mvcboot02.pojo.dto.AddUserDto;
import cn.tedu._05mvcboot02.pojo.entity.User;
import cn.tedu._05mvcboot02.pojo.vo.UserListVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;

//@Controller

/**
 * RestController注解
 * 1.组合注解：想当于Controller+ResponseBody
 * 2.在控制器类中加入该注解后，无需在每个方法上添加 @ResponseBody 注解；
 * 可以让Spring框架自动将方法的返回值序列化并填充到HTTP响应中，实现Web服务端点的快速开
 * 发
 */
@RestController
/**
 * 在类上添加@RequestMapping注解，填写相同部分的地址
 * 1.类中注解：@RequestMapping("/v1/users/")
 * 2.方法注解：@RequestMapping("login")
 */
@RequestMapping(value = "/v1/users/")
@Slf4j
@Api(tags= "01.用户模块")
public class UserController {
    @Autowired
    private UserMapper  userMapper;
    /**
     * 1.添加用户功能
     * @return
     */
    @PostMapping(value = "insert")
    @ApiOperation(value = "添加用户功能")
    public JsonResult addUser(AddUserDto addUserDto){
        log.debug("addUserDto = "+addUserDto);
        User user = new User();
        BeanUtils.copyProperties(addUserDto,user);
        user.setCreated(new Date());
        userMapper.insertUser(user);
        return JsonResult.ok();
    }

    /**
     *2.查询用户列表
     */
    @GetMapping(value = "userList")
    @ApiOperation(value = "查询用户列表功能")
    public JsonResult userListVo(){
        log.debug("userListVo={}"+userMapper.selectUserList());
        return JsonResult.ok(userMapper.selectUserList());
    }
    /**
     * 3.删除指定用户
     */
    @GetMapping(value = "delete")
    @ApiOperation(value = "删除指定用户功能")
    @ApiImplicitParam(name = "id",value = "用户ID",required = true,dataType = "int")
    public JsonResult deleteUser(int id){
        if (id <0) {
            throw new IllegalArgumentException("ID值不能小于0");
        }
        userMapper.deleteById(id);
        return JsonResult.ok();
    }

    /**
     * 4.更新用户
     */
    @PostMapping(value = "update")
    @ApiOperation(value = "更新用户功能")
    public JsonResult updateUser(User user){
        log.debug("user = "+user);
        userMapper.updateUser(user);
        return JsonResult.ok();
    }

    /**
     * 5.根据 id 查询用户，并返回该用户信息（ GET请求：/v1/users/{id} ）
     */
    @GetMapping(value = "{id}")
    @ApiOperation(value = "根据ID查询用户功能")
    @ApiImplicitParam(name = "id",value = "用户ID",required = true,dataType = "Integer")
    public JsonResult getUserById(@PathVariable Integer id){
        log.debug("id = "+id);
        return JsonResult.ok(userMapper.selectById(id));
    }


}
